package com.linchong.concurrency.basic;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author linchong
 * @version 1.0
 * @Date: 2020-12-08 11:23
 * @Description: MapExample$
 */
@Slf4j
public class MapExample {

	private static Map<Integer,Integer> map = Maps.newHashMap();
	/**
	 * 请求处理次数，每次允许200次请求同时执行
	 */
	private static final int THREAD_NUM = 200;

	/**
	 * 短时间内接收的总的请求数
	 */
	private static final int CLIENT_NUM = 5000;

	public static void main(String[] args) {
		ExecutorService exec = Executors.newCachedThreadPool();
		final Semaphore semaphore = new Semaphore(THREAD_NUM);
		for (int index = 0; index < CLIENT_NUM; index++) {
			final int threadNum = index;
			exec.execute(()->{
				try {
					semaphore.acquire();
					func(threadNum);
					semaphore.release();
				} catch (InterruptedException e) {
					log.error("exception",e);
				}
			});
		}
		exec.shutdown();
		log.info("size:{}",map.size());
	}

	public static void func(int threadNum){
		map.put(threadNum,threadNum);
	}
}
